/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package filter

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/comm"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/context"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
)

type EndpointType int32

const (
	ContractQuery EndpointType = iota
	EndorsingInode
	LedgerQuery
	EventSource
)

func NewEndpointFilter(ctx context.Chain, et EndpointType) *EndpointFilter {

	chInodes := ctx.EndpointConfig().ChainInodes(ctx.ChainID())
	return &EndpointFilter{endpointType: et, ctx: ctx, chInodes: chInodes}

}

type EndpointFilter struct {
	endpointType EndpointType
	ctx          context.Chain
	chInodes     []ichain.ChainInode // configured chain inodes
}

func (f *EndpointFilter) Accept(inode ichain.Inode) bool {

	inodeConfig, err := comm.SearchInodeConfigFromURL(f.ctx.EndpointConfig(), inode.URL())
	if err != nil {
		return true
	}

	chInode := f.getChainInode(inodeConfig)
	if chInode == nil {
		return true
	}

	switch t := f.endpointType; t {
	case ContractQuery:
		return chInode.ContractQuery
	case EndorsingInode:
		return chInode.EndorsingInode
	case LedgerQuery:
		return chInode.LedgerQuery
	case EventSource:
		return chInode.EventSource
	}

	return true
}

func (f *EndpointFilter) getChainInode(inodeConfig *ichain.InodeConfig) *ichain.ChainInode {
	for _, chinode := range f.chInodes {
		if chinode.URL == inodeConfig.URL {
			return &ichain.ChainInode{
				InodeChainConfig: chinode.InodeChainConfig,
				NetworkInode:     chinode.NetworkInode,
			}
		}
	}
	return nil
}
